Protocols and structural subtyping
https://mypy.readthedocs.io/en/latest/protocols.html
Mypy supports two ways of deciding whether two classes are compatible as types: nominal subtyping and structural subtyping.
Nominal subtyping is strictly based on the class hierarchy.
If class D inherits class C, it’s also a subtype of C, and instances of D can be used when C instances are expected.
「クラスDがクラスCを継承しているならば、DはCのサブタイプで、DのインスタンスはCのインスタンスが期待されるときに使うことができる」
This form of subtyping is used by default in mypy, since it’s easy to understand and produces clear and concise error messages, and since it matches how the native isinstance check works – based on class hierarchy.
Structural subtyping can also be useful. Class D is a structural subtype of class C if the former has all attributes and methods of the latter, and with compatible types.
「クラスDはクラスCの属性とメソッド全てを互換な型と一緒に持つとき、DはCの構造的なサブタイプである」
特にメソッドでシグネチャ(型情報)が一致!
Structural subtyping can be seen as a static equivalent of duck typing, which is well known to Python programmers.
「構造的サブタイピングはダックタイピングの静的なものに相当する」(ダックタイピングは動的)
Predefined protocolsを紹介
Iteration
Collection
One-off
These protocols are typically only useful with a single standard library function or class.
Async
Context manager
Simple user-defined protocols
SupportsCloseを定義する例
Using isinstance() with protocols
@runtime_checkable